package com.welike.shibo.utils;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Client;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author fangyu
 * @version v1.0.0
 * @since 2019-08-23 00:33
 */

@Slf4j
@Component
public class QiNiuUtil {

    private String accessKey = "sFof1xq7Szqpn5xN_zfHLYQohHSPXcHZ87CBkv7y";
    private String secretKey = "vCrGGCOgdMwyEHejZKD4Bjjg1bxCmbGvQDrGybOC";
//    private String bucket = "health";
    private String bucket = "jdshortvideo";
//    private String doMain = "http://pwe4y2ao3.bkt.clouddn.com/";
//    private String doMain = "http://cdn.health.healthplatform.xyz/";
//    private String doMain = "http://shortvideo.healthplatform.xyz/";

    private UploadManager uploadManager;
    private BucketManager bucketManager;

    private Configuration c;
    private Client client;

    // 密钥配置
    private Auth auth;

    public Client getClient(){
        if (client == null){
            client = new Client(getConfiguration());
        }
        return client;
    }

    public BucketManager getBucketManager(){
        if (bucketManager == null){
            bucketManager = new BucketManager(getAuth(), getConfiguration());
        }
        return bucketManager;
    }

    public UploadManager getUploadManager() {
        if (uploadManager == null){
            uploadManager = new UploadManager(getConfiguration());
        }
        return uploadManager;
    }

    public Auth getAuth(){
        if (auth == null){
            auth = Auth.create(accessKey, secretKey);
        }
        return auth;
    }

    public Configuration getConfiguration(){
        if (c == null){
            Zone zone = Zone.autoZone();
            c = new Configuration(zone);
        }
        return c;
    }

    /**
     * 获取上传模式的凭证
     * @return
     */
    public String getUpToken() {
        return getAuth().uploadToken(bucket);
    }

    //覆盖上传模式的凭证
    public String getUpToken(String key) {
        return getAuth().uploadToken(bucket, key);
    }


    /**
     *
     * @param filePath 文件路径
     * @param key 文件key，名字
     * @return 上传结果
     * @throws IOException IO异常
     */
    public String upload(String filePath, String key) throws IOException {
        Response response;
        try {
            log.info("upload == filePath=>{}, key=>{}", filePath, key);
            response = getUploadManager().put(filePath, key, getUpToken(key));
            // 解析上传结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
//            return doMain + putRet.key;
            return putRet.key;
        } catch (QiniuException e){
            response = e.response;
            log.error("upload fail: {}", response);
            log.error("upload fail: {}", e.getMessage());
            return "error";
        }

    }


    /**
     * 上传FileInputStream流
     * @param file 文件流
     * @param key 文件key，名字
     * @return 上传结果
     * @throws IOException IO异常
     */
    public String uploadQiNiu(FileInputStream file, String key) throws IOException {
        Response response;
        try {
            response = getUploadManager().put(file, key, getUpToken(key), null, null);
            // 解析上传结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
//            return doMain + putRet.key;
            return putRet.key;
        } catch (QiniuException e) {
            log.error("QiniuException e: {}", e.getMessage());
            return "error";
        }
    }

    /**
     * 上传输入流
     * @param inputStream 输入流
     * @param key 文件key，名字
     * @return 上传结果
     * @throws IOException IO异常
     */
    public String upload(InputStream inputStream, String key) throws IOException {
        Response res;
        try {
            res = getUploadManager().put(inputStream, key, getUpToken(key),null,null);
            // 解析上传结果
            DefaultPutRet putRet = new Gson().fromJson(res.bodyString(), DefaultPutRet.class);
//            return doMain + putRet.key;
            return putRet.key;
        } catch (QiniuException e) {
            log.error("QiniuException e: {}", e.getMessage());
            e.printStackTrace();
            return "error";
        }
    }

    /**
     * 上传图片
     * @param filePath 输入流
     * @param key 文件key，名字
     * @return 上传结果 Boolean
     * @throws IOException IO异常
     */
    public Boolean uploadImg(String filePath, String key) throws IOException {
        try {
            getUploadManager().put(filePath, key, getUpToken(key));
            return true;
        } catch (QiniuException e){
            log.error("QiniuException ==> {}", e.getMessage());
            return false;
        }
    }
}
